<script setup lang="ts">
import VChart from "@/views/monitor/server/components/VChart.vue";
import { onMounted, reactive, ref, watch } from "vue";
import moment from "moment";
import { useRoute } from "vue-router";
import { RefreshLeft, Search } from "@element-plus/icons-vue";
import { ElForm } from "element-plus";
import { getStoreDaUser } from "@/api/predictingTrends";
import { dayRangeArray, timeSlot } from "@/utils";
import { getVppUserListAll } from "@/api/vppUser";
const route = useRoute();
const activeUserId = ref(route.query?.id);
const activeStoreId = ref(route.query?.storeId);
const activeName = ref("first");
const allUser = reactive({
  data: []
});
const queryForm = reactive({
  data: {
    activeUserId: activeUserId.value,
    activeStoreId: activeStoreId.value,
    activeTime: []
  }
});
const options = ref({
  dataZoom: [
    {
      show: true,
      type: "inside",
      start: 0,
      end: 100
    },
    {
      show: true,
      type: "slider",
      start: 0,
      end: 100
    }
  ],
  tooltip: {
    show: true,
    trigger: "axis"
  },
  legend: {
    show: true,
    data: ["实际值", "计划值"]
  },
  xAxis: {
    type: "category",
    axisLabel: {
      //x轴文字的配置
      show: true
      // interval: 0,//使x轴文字显示全
    },
    splitLine: {
      show: true,
      interval: (index, value) => {
        if (value.indexOf("00:00:00") > -1) {
          return true;
        } else {
          return false;
        }
      },
      lineStyle: {
        type: "solid",
        width: 1.3
      }
    },
    boundaryGap: false,
    data: []
  },
  yAxis: {
    name: "kW",
    nameLocation: "end",
    type: "value",
    min: "dataMin",
    axisLabel: {
      show: true
    }
  },
  series: [
    {
      name: "实际值",
      type: "line",
      showSymbol: false,
      smooth: true,
      data: []
    },
    {
      name: "计划值",
      type: "line",
      showSymbol: false,
      smooth: true,
      data: []
    }
  ]
});
const allStoreUser = reactive({
  data: []
});
const temChange = e => {
  queryForm.data.activeStoreId = undefined;
  if (e) {
    let p = allUser.data.find(i => i.id === e);
    allStoreUser.data = p
      ? p.storageInfos
        ? p.storageInfos.map(i => ({ ...i, id: i.id + "" }))
        : []
      : [];
  } else {
    allStoreUser.data = [];
  }
};
const loading = ref(false);
const init = async () => {
  let res = await getVppUserListAll();
  allUser.data = res.map(i => ({ ...i, id: i.id + "" }));
  queryForm.data.activeTime = [
    moment().subtract("day", -1).subtract("month", 3).format("YYYY-MM-DD"),
    moment().subtract("day", -1).format("YYYY-MM-DD")
  ];
  if (queryForm.data.activeUserId) {
    loading.value = true;
    let p = allUser.data.find(i => i.id === activeUserId.value);
    allStoreUser.data = p
      ? p.storageInfos
        ? p.storageInfos.map(i => ({ ...i, id: i.id + "" }))
        : []
      : [];
    let data = await getStoreDaUser({
      vppStorId: queryForm.data.activeStoreId,
      begin: queryForm.data.activeTime[0],
      end: queryForm.data.activeTime[1]
    });
    dataFormat(data);
    loading.value = false;
  } else {
    dataFormat([]);
  }
};

const search = async () => {
  if (
    queryForm.data.activeStoreId &&
    queryForm.data.activeTime &&
    queryForm.data.activeTime.length
  ) {
    loading.value = true;
    let data = await getStoreDaUser({
      vppStorId: queryForm.data.activeStoreId,
      begin: queryForm.data.activeTime[0],
      end: queryForm.data.activeTime[1]
    });
    dataFormat(data);
    loading.value = false;
  } else {
    dataFormat([]);
  }
};
const resetQuery = () => {
  queryForm.data = {
    activeUserId: route.query?.id,
    activeTime: [
      moment().subtract("day", -1).subtract("month", 3).format("YYYY-MM-DD"),
      moment().subtract("day", -1).format("YYYY-MM-DD")
    ]
  };
};
const times = ref(timeSlot(15));
const keys = ref(
  Array(96)
    .fill(1)
    .map((_, index) => index + 1)
    .map(i => `p${i > 9 ? i : "0" + i}`)
);
const showData = reactive({
  data: []
});
const dataFormat = data => {
  let days = [];
  if (queryForm.data.activeTime && queryForm.data.activeTime.length) {
    days = dayRangeArray(
      queryForm.data.activeTime[0],
      queryForm.data.activeTime[1]
    );
  } else {
    days = [];
  }
  let allData = [];
  let xData = [];
  days.forEach(i => {
    let item = {};
    item.dataDate = i + " 00:00:00";
    keys.value.forEach(key => {
      item[key] = null;
    });
    item.dataType = 1;
    allData.push(item);
    let item2 = {};
    item2.dataDate = i + " 00:00:00";
    keys.value.forEach(key => {
      item2[key] = null;
    });
    item2.dataType = 2;
    allData.push(item2);
  });
  for (let i = 0; i < allData.length; i++) {
    for (let j = 0; j < data.length; j++) {
      if (
        allData[i].dataDate === data[j].dataDate &&
        allData[i].dataType === data[j].dataType
      ) {
        allData[i] = Object.assign({}, allData[i], data[j]);
      }
    }
  }
  const ret = {};
  allData.forEach(i => {
    ret[i.dataDate] = {
      "1": {},
      "2": {}
    };
  });
  allData.forEach(i => {
    ret[i.dataDate][i.dataType + ""] = i;
  });

  let oneData = allData.filter(i => i.dataType === 1);
  let twoData = allData.filter(i => i.dataType === 2);
  let isd = [];
  let tsd = [];
  oneData.forEach(i => {
    times.value.forEach((z, index) => {
      xData.push(i.dataDate.split(" ")[0] + " " + z + ":00");
      isd.push({
        value: i[keys.value[index]]
      });
    });
  });
  let start = (1 - 96 / xData.length) * 100;
  options.value.xAxis.data = xData;
  options.value.dataZoom[0].start = start;
  options.value.dataZoom[1].start = start;

  twoData.forEach(i => {
    times.value.forEach((z, index) => {
      tsd.push({
        value: i[keys.value[index]]
      });
    });
  });
  options.value.series[0].data = isd;
  options.value.series[1].data = tsd;
  showData.data = [];
  xData.forEach((item, index) => {
    let v = {
      label: item,
      value1: isd[index].value,
      value2: tsd[index].value
    };
    showData.data.push(v);
  });
  showData.data.sort((a, b) => {
    return Date.parse(a.label) - Date.parse(b.label);
  });
};
const columns = [
  {
    key: "label",
    dataKey: "label",
    title: "时间",
    width: "30%"
  },
  {
    key: "value1",
    dataKey: "value1",
    title: "实际值",
    width: "30%"
  },
  {
    key: "value2",
    dataKey: "value2",
    title: "计划值",
    width: "30%"
  }
];
const shortcuts = [
  {
    text: "最近一周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    }
  },
  {
    text: "最近一月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    }
  },
  {
    text: "最近三月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    }
  }
];
onMounted(() => {
  init();
});
</script>

<template>
  <div class="main h-[calc(100%-29px)]">
    <el-card v-loading="loading" class="w-full my-card-full">
      <el-form :inline="true" :model="queryForm.data" label-width="0px">
        <el-form-item>
          <el-select
            v-model="queryForm.data.activeUserId"
            placeholder="选择用户"
            style="width: 240px"
            @change="temChange"
          >
            <el-option
              v-for="item in allUser.data"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="queryForm.data.activeStoreId"
            placeholder="选择储能用户"
            style="width: 240px"
          >
            <el-option
              v-for="item in allStoreUser.data"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="queryForm.data.activeTime"
            unlink-panels
            type="daterange"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD"
            date-format="YYYY-MM-DD"
            :shortcuts="shortcuts"
          />
        </el-form-item>
        <el-form-item class="ml-[10px]">
          <el-button type="primary" :icon="Search" @click="search"
            >查询</el-button
          >
          <el-button :icon="RefreshLeft" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-tabs v-model="activeName" class="demo-tabs">
        <el-tab-pane label="图表" name="first">
          <div class="w-full h-full">
            <v-chart :options="options" />
          </div>
        </el-tab-pane>
        <el-tab-pane label="列表" name="second">
          <div>
            <el-table-v2
              :columns="columns"
              :data="showData.data"
              :width="1614"
              :height="600"
              :scrollbar-always-on="false"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>
<style lang="scss" scoped>
.my-card-full {
  :deep(.el-card__body) {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;

    .demo-tabs {
      display: flex;
      flex: 1;
      flex-direction: column;
      overflow: hidden;

      .el-tabs__content {
        flex: 1;

        .el-tab-pane {
          width: 100%;
          height: 100%;
        }
      }
    }
  }
}
</style>
